App({
  globalData: {
    userInfo: null,
    token: null,
    baseURL: 'http://localhost:8080/api/v1'
  },

  onLaunch() {
    // 检查登录状态
    const token = wx.getStorageSync('token')
    if (token) {
      this.globalData.token = token
      this.getUserInfo()
    }
  },

  // 获取用户信息
  getUserInfo() {
    return this.request('/users/profile', 'GET')
      .then(res => {
        this.globalData.userInfo = res.data
        return res.data
      })
      .catch(err => {
        console.error('获取用户信息失败:', err)
        return null
      })
  },

  // 统一请求方法
  request(url, method = 'GET', data = {}) {
    const header = {
      'Content-Type': 'application/json'
    }
    
    if (this.globalData.token) {
      header['Authorization'] = `Bearer ${this.globalData.token}`
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.globalData.baseURL}${url}`,
        method,
        data,
        header,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else if (res.statusCode === 401) {
            // token过期，清除登录状态
            this.globalData.token = null
            this.globalData.userInfo = null
            wx.removeStorageSync('token')
            reject(new Error('请重新登录'))
          } else {
            reject(new Error(res.data.message || '请求失败'))
          }
        },
        fail: (err) => {
          reject(new Error('网络请求失败'))
        }
      })
    })
  },

  // 微信登录
  wechatLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            this.request('/auth/wechat-login', 'POST', { code: res.code })
              .then(result => {
                this.globalData.token = result.data.token
                this.globalData.userInfo = result.data.user
                wx.setStorageSync('token', result.data.token)
                resolve(result)
              })
              .catch(reject)
          } else {
            reject(new Error('微信登录失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 获取手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      return Promise.reject(new Error('获取手机号失败'))
    }
    
    return this.request('/auth/phone-login', 'POST', {
      code: '',
      phone_code: e.detail.code
    })
  }
})